﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Shell;
using PictureSearch.AppCode;
using PictureSearch.BingService;

namespace PictureSearch
{
    public partial class MainPage
    {
        private const string defaultQueryText = "Input here to find pictures...";
        private const int maxItemsToShow = 7;

        private readonly BingPortTypeClient searchClient = new BingPortTypeClient();
        private SearchResponse response;

        private int responseOffset;

        private bool isGalleryLoaded;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();

            this.searchClient.SearchCompleted +=
                (obj, arg) =>
                {
                    try
                    {
                        if (arg.Error != null)
                        {
                            this.Dispatcher.BeginInvoke(() => ShowLoading(false, string.Empty));
                            MessageBox.Show("Connect failed. Please check your network and try later.");
                        }
                        else
                        {
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    ShowLoading(false, string.Empty);

                                    response = arg.Result;

                                    if (response.Image.Results == null)
                                    {
                                        MessageBox.Show("No results where found. ");
                                    }
                                    else
                                    {
                                        ClearSearchResults();

                                        DisplayImage();
                                    }
                                });
                        }
                    }
                    catch(Exception)
                    {
                        MessageBox.Show("Search failed, plesase try again");
                    }
                    
                };
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            var msgRst = MessageBox.Show("Search results may contain adult content.\n\rDo you want to continue?", "Warning", MessageBoxButton.OKCancel);

            if (msgRst == MessageBoxResult.Cancel)
            {
                this.PivotSearch.IsEnabled = false;
            }

            txtQueryText.Text = defaultQueryText;
        }

        private void btnSearchNav_Click(object sender, RoutedEventArgs e)
        {
            pivot.SelectedIndex = 1;
        }

        private void btnGalleryNav_Click(object sender, RoutedEventArgs e)
        {
            pivot.SelectedIndex = 2;
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplicationBar.IsVisible = pivot.SelectedIndex == 0;

            if (popGalleryShowItem.IsOpen)
            {
                popGalleryShowItem.IsOpen = false;
                wpGallery.IsHitTestVisible = true;
            }

            if (popSaveImage.IsOpen)
            {
                popSaveImage.IsOpen = false;
                svImages.IsHitTestVisible = true;
            }

            if (pivot.SelectedIndex == 2)
            {
                LoadGallery();
            }
        }

        #region Pivot Search

        private void DisplayImage()
        {
            int count = 0;

            for (int i = responseOffset; i < response.Image.Results.Count(); i++)
            {
                responseOffset++;

                if (count >= maxItemsToShow)
                {
                    break;
                }

                if (
                        response.Image.Results[i].ContentType.Contains("jpg")
                        || response.Image.Results[i].ContentType.Contains("jpeg")
                        || response.Image.Results[i].ContentType.Contains("jpe")
                        || response.Image.Results[i].ContentType.Contains("jfif")
                        || response.Image.Results[i].ContentType.Contains("png")
                    )
                {
                    count++;

                    ImageItem item = new ImageItem
                        (
                            response.Image.Results[i].Width,
                            response.Image.Results[i].Height
                        );

                    item.Hold += (sender, args) =>
                                     {
                                         // Jodge Image has finished loading
                                         if (item.IsLoaded)
                                         {
                                             svImages.IsHitTestVisible = false;

                                             popSaveImage.IsOpen = true;

                                             currentImage.Source = item.image.Source;
                                         }
                                     };

                    spImages.Children.Insert((spImages.Children.Count - 1) > 0 ? spImages.Children.Count - 1 : 0, item);

                    item.SetImageUrl(response.Image.Results[i].MediaUrl);
                }
            }

            if (responseOffset < response.Image.Results.Count())
            {
                btnMore.Visibility = Visibility.Visible;
            }
        }

        private void btnLoading_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            btn.Visibility = Visibility.Collapsed;

            this.Dispatcher.BeginInvoke(DisplayImage);
        }

        private void ClearSearchResults()
        {
            responseOffset = 0;

            var btn = this.btnMore;
            spImages.Children.Clear();
            spImages.Children.Add(btn);
            btn.Visibility = Visibility.Collapsed;

            popSaveImage.IsOpen = false;
            svImages.IsHitTestVisible = true;
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            this.Focus();

            ClearSearchResults();

            ShowLoading(true, "Searching...");

            ImageRequest imageRequest = new ImageRequest
            {
                Offset = 0,
                OffsetSpecified = true,
                Count = 50,
                CountSpecified = true,
                //Filters = new[] {"Size:Height:800", "Size:Width:400"}
            };

            string queryString = string.Format("{0}", txtQueryText.Text.Trim());

            var searchRequest = new SearchRequest
                                    {
                                        AppId = "48C6DD50BC2845088A3A6402D3DB003A66A8AE70",
                                        Market = CultureInfo.CurrentCulture.Name,
                                        Sources = new[] {SourceType.Image, SourceType.Spell},
                                        Query = queryString,
                                        Image = imageRequest,
                                        AdultSpecified = true,
                                        Adult = AdultOption.Strict
                                    };

            this.searchClient.SearchAsync(searchRequest);

            ShowTipInSearch.Begin();
        }

        private void txtQueryText_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnSearch.IsEnabled = !string.IsNullOrWhiteSpace(txtQueryText.Text);
        }

        private static void ShowLoading(bool show, string text)
        {
            if (show && !SystemTray.IsVisible)
            {
                SystemTray.IsVisible = true;
            }

            SystemTray.ProgressIndicator.Text = text;
            SystemTray.ProgressIndicator.IsVisible = show;
        }

        private void txtQueryText_GotFocus(object sender, RoutedEventArgs e)
        {
            txtQueryText.SelectAll();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        string fileName = ImageCommon.SaveImage(currentImage.Source);

                        if (isGalleryLoaded)
                        {
                            GalleryItem image = new GalleryItem(fileName) {Width = 145, Height = 145};
                            image.Hold += (o, args) =>
                                              {
                                                  txtImageFileName.Text = image.FileName;
                                                  galleryImage.Source = image.image.Source;
                                                  popGalleryShowItem.IsOpen = true;
                                                  wpGallery.IsHitTestVisible = false;
                                              };

                            wpGallery.Children.Insert(0, image);
                        }

                        btnCancel_Click(sender, e);
                    });

            // Save story broad
            SaveSuccess.Begin();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        popSaveImage.IsOpen = false;
                        svImages.IsHitTestVisible = true;
                    });
        }

        #endregion

        #region Pivot Gallery

        private void LoadGallery()
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        if (!isGalleryLoaded)
                        {
                            // Clear Gallery
                            wpGallery.Children.Clear();

                            // Get images list
                            string[] list = ImageCommon.GetImageList();

                            if (list != null)
                            {
                                foreach (var imageFile in list)
                                {
                                    GalleryItem galleryItem = new GalleryItem(imageFile) {Width = 150, Height = 150};

                                    galleryItem.Hold += (sender, args) =>
                                                            {
                                                                txtImageFileName.Text = galleryItem.FileName;
                                                                galleryImage.Source = galleryItem.image.Source;
                                                                popGalleryShowItem.IsOpen = true;
                                                                wpGallery.IsHitTestVisible = false;
                                                            };

                                    wpGallery.Children.Add(galleryItem);
                                }

                                isGalleryLoaded = true;
                            }
                        }
                    });
        }

        private void btnGallerySave_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        var msgRst = MessageBox.Show("Save this image to Camera Roll？", "Comfirm", MessageBoxButton.OKCancel);

                        if (msgRst == MessageBoxResult.OK)
                        {
                            try
                            {
                                // Save to lacal
                                ImageCommon.SaveToAlbum(txtImageFileName.Text);

                                MessageBox.Show("Image has saved in your PHONE \r\nYou can get it from Camera Roll");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }

                            btnGalleryCancel_Click(sender, e);
                        }
                    });
        }

        private void btnGalleryDelete_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        var msgRst = MessageBox.Show("Delete this image？", "Comfirm", MessageBoxButton.OKCancel);

                        if (msgRst == MessageBoxResult.OK)
                        {
                            // Delete file
                            ImageCommon.DeleteImage(txtImageFileName.Text);
                            // Delete file in Gallery
                            foreach (GalleryItem item in wpGallery.Children)
                            {
                                if (item.FileName == txtImageFileName.Text)
                                {
                                    wpGallery.Children.Remove(item);
                                    break;
                                }
                            }

                            btnGalleryCancel_Click(sender, e);
                        }
                    });
        }

        private void btnGalleryCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                    {
                        popGalleryShowItem.IsOpen = false;
                        wpGallery.IsHitTestVisible = true;
                    });
        }
        #endregion

        private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
        {
            if (popGalleryShowItem.IsOpen)
            {
                popGalleryShowItem.IsOpen = false;
                wpGallery.IsHitTestVisible = true;

                e.Cancel = true;
                return;
            }

            if (popSaveImage.IsOpen)
            {
                popSaveImage.IsOpen = false;
                svImages.IsHitTestVisible = true;

                e.Cancel = true;
                return;
            }

            if (pivot.SelectedIndex > 0)
            {
                pivot.SelectedIndex--;

                e.Cancel = true;
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if(txtQueryText.Text == defaultQueryText)
            {
                App.QueryTxt = string.Empty;
            }
            else
            {
                App.QueryTxt = txtQueryText.Text;
            }

            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(App.QueryTxt))
            {
                txtQueryText.Text = App.QueryTxt;
                btnSearch_Click(null, null);
            }

            base.OnNavigatedTo(e);
        }

        private void menuAbout_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }
    }
}